import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:homepad/logger/logger.dart';

class WeatherInfo {
  final String province;
  final String city;
  final String weather;
  final String temperature;
  final String reportTime;

  WeatherInfo({
    required this.province,
    required this.city,
    required this.weather,
    required this.temperature,
    required this.reportTime,
  });

  factory WeatherInfo.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        "province": String province,
        "city": String city,
        "weather": String weather,
        "temperature": String temperature,
        "reporttime": String reportTime,
      } =>
        WeatherInfo(
          province: province,
          city: city,
          weather: weather,
          temperature: temperature,
          reportTime: reportTime,
        ),
      _ => throw const FormatException("failed to load weatherInfo"),
    };
  }

  @override
  String toString() {
    return "$reportTime $city: $weather -> $temperature";
  }
}

class WeatherModel extends ChangeNotifier {
  WeatherInfo? _info;
  WeatherInfo? get info => _info;

  final city = "440306";
  final key = "67d9dcd06a58176297925c84a2427cca";

  WeatherModel() {
    runZoned(() async {
      var info = await fetchWeatherInfo(city, key);
      if (info != null) {
        _info = info;
        logger.info(info);
        notifyListeners();
      }
      Timer.periodic(const Duration(minutes: 1), (timer) async {
        DateTime now = DateTime.now();
        if (now.minute % 15 != 0) {
          return;
        }
        var info = await fetchWeatherInfo(city, key);
        if (info != null) {
          _info = info;
          logger.info(info);
          notifyListeners();
        }
      });
    });
  }

  Future<WeatherInfo?> fetchWeatherInfo(String city, String key) async {
    final uri = Uri(
        scheme: "https",
        host: "restapi.amap.com",
        path: "/v3/weather/weatherInfo",
        queryParameters: {"extension": "base", "city": city, "key": key});

    try {
      final response = await http.get(uri);
      if (response.statusCode != 200) {
        logger.error("status.code=${response.statusCode}");
        return null;
      }

      final responseJson = jsonDecode(response.body) as Map<String, dynamic>;
      var live = (responseJson["lives"] as List<dynamic>?)?.first;
      if (live == null) {
        return null;
      }

      final info = WeatherInfo.fromJson(live as Map<String, dynamic>);
      return info;
    } catch (e) {
      logger.error(e.toString());
    }
    return null;
  }
}
